#include <my_header.h>

/* Usage: ./15_gettimeofday */
// 两个线程对同一个共享变量分别加一百万次: 使用锁: 计算时间
#define TIMES 10000000
// 创建结构体
typedef struct share_value{
    int sum;
    pthread_mutex_t mLock;
} share_value_t;

void * func(void *arg){

    share_value_t *pshareValue = (share_value_t *)arg;
    printf("child thread is runing \n");
    for(int i = 0; i<TIMES; i++){
        pthread_mutex_lock(&pshareValue->mLock);
        pshareValue->sum ++;
        pthread_mutex_unlock(&pshareValue->mLock);
    }
    printf("child thread stop \n");
}

int main(int argc,char*argv[])
{
    struct timeval beginTime, endTime;
    gettimeofday(&beginTime, NULL);

    share_value_t shareValue;
    shareValue.sum = 0;
    pthread_mutex_init(&shareValue.mLock, NULL);

    pthread_t pid;
    pthread_create(&pid,NULL,func, &shareValue);

    printf("main thread is runing \n");
    for(int i = 0; i<TIMES; i++){
        pthread_mutex_lock(&shareValue.mLock);
        shareValue.sum++;
        pthread_mutex_unlock(&shareValue.mLock);
    }
    printf("main thread stop \n");

    pthread_join(pid, NULL);
    printf("all over, global = %d \n", shareValue.sum);

    pthread_mutex_destroy(&shareValue.mLock);
    // 结束时间
    gettimeofday(&endTime, NULL);
    // 打印时间
    printf("time: %ld  us \n", endTime.tv_usec - beginTime.tv_usec + (endTime.tv_sec - beginTime.tv_sec)*1000000);
    return 0;
}

